<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 一有序数组，给一个 target 值，找数组是否存在，存在返回对应的索引值，不存在按顺序插入 target 并返回插入的索引值
      function findNum(arr, target) {
        let left = 0
        let right = arr.length - 1
        while (left <= right) {
          let mid = Math.floor((left + right) / 2)
          if (arr[mid] === target) {
            return mid
          } else if (arr[mid] > target) {
            right = mid - 1
          } else {
            left = mid + 1
          }
        }
        return left // 未寻找到 target 值时的 left 值为刚好大过 target 的索引值
      }
      console.log(findNum([1, 3, 5, 7], 2))
    </script>
  </body>
</html>
